package cn.wolfcode.luowowo.resolver;

import cn.wolfcode.luowowo.annotion.UserParam;
import cn.wolfcode.luowowo.cache.service.IUserInfoRedisService;
import cn.wolfcode.luowowo.domain.UserInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.data.annotation.Reference;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.HttpServletRequest;

/**
 * 请求映射方法参数解析器
 *
 * 注入当前登录用户对象
 */
public class UserInfoArgumentResolver implements HandlerMethodArgumentResolver{

    //指定当前解析器能支持解析的参数类型
    //返回值是true或者false: true表示支持解析指定参数,false表示不支持指定参数
    //当前登录用户对象: UserInfo

    @Autowired
    private IUserInfoRedisService userInfoRedisService;

    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return parameter.getParameterType() == UserInfo.class && parameter.hasParameterAnnotation(UserParam.class);
    }
    //如果supportsParameter方法返回true时才执行
    //执行获取当前登录用户信息对象,将返回值注入到请求映射方法声明的UserInfo类型的形式参数中
    @Override
    public Object resolveArgument(MethodParameter parameter,
                                  ModelAndViewContainer modelAndViewContainer, NativeWebRequest nativeWebRequest,
                                  WebDataBinderFactory webDataBinderFactory) throws Exception {
        //获取当前登录用户对象,然后返回
        HttpServletRequest request = nativeWebRequest.getNativeRequest(HttpServletRequest.class);
        String token = request.getHeader("token");
        UserInfo user = userInfoRedisService.getUserByToken(token);
        return user;
    }
}